//
//  MusicPlayer1.m
//  YanMusicPlayer
//
//  Created by 1564335 on 15-6-22.
//  Copyright (c) 2015年 胡岩 All rights reserved.
//

#import "MusicPlayer1.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"
@implementation MusicPlayer1
+ (MusicPlayer1 *)shareInstance
{
    static MusicPlayer1 *musicPlayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        musicPlayer = [[MusicPlayer1 alloc] init];
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [session setActive:YES error:nil];
        [UIApplication sharedApplication].statusBarHidden = YES;
    });
    return musicPlayer;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        _collectList = [NSMutableArray array];
        _downloadList = [NSMutableArray array];
        _moviePlayer = [[MPMoviePlayerController alloc] init];
        _list = [NSMutableArray array];
        _mainList = [NSMutableArray array];
        _lrc = [NSString string];
        _isDownLoad = NO;
        _isDownLoadList = NO;
        _isPlay = NO;
        _firstPlay = NO;
        _currentMusic = 0;
        _orderManager = 0;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(autoNextMusicPlay)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initSongInfomation)
                                                 name: MPMoviePlayerLoadStateDidChangeNotification
                                               object:nil];
    
    return self;
}

- (void)autoNextMusicPlay
{
    if (_list.count == 0) {
        [_moviePlayer pause];
        _isPlay = NO;
        [HearderView shareInstance].progressSlider.value = 0;
        [[HearderView shareInstance].timer invalidate];
        [[HearderView shareInstance].imageTurnTimer invalidate];
        [[HearderView shareInstance].lrcTimer invalidate];
        [_moviePlayer setContentURL:nil];
        [HearderView shareInstance].title.text = nil;
        [HearderView shareInstance].singerName.text = nil;
        [HearderView shareInstance].currentTime.text = @"00:00";
        [HearderView shareInstance].totalTimeLabel.text = @"00:00";
        _titleImage.image = [UIImage imageNamed:@"placeholder"];
        [[HearderView shareInstance].backgroundImageView setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"bgImage"]];
        [[HearderView shareInstance].titleImageView setImage:[UIImage imageNamed:@"placeholder"]];
        [[HearderView shareInstance].LRCDictionary removeAllObjects];
        [[HearderView shareInstance].timeArray removeAllObjects];
        [[HearderView shareInstance].lrcTableView reloadData];
        [[HearderView shareInstance].listTableView reloadData];
        [[HearderView shareInstance].progressBar setProgress:0.0 animated:NO];
        [[HearderView shareInstance].startButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        [HearderView shareInstance].centreView.alpha = 0.8;
        return;
    }
    if (_orderManager == 0 && _list.count - 1 == _currentMusic) {
        _currentMusic = 0;
        //        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[MusicPlayer1 shareInstance].currentMusic inSection:0];
        //        [[HearderView shareInstance].listTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        MusicModel *model = [_list objectAtIndex:_currentMusic];
        if ([MusicPlayer1 shareInstance].isDownLoad) {
            NSString *homePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            NSString *url = [homePath stringByAppendingPathComponent:model.url];
            [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL fileURLWithPath:url]];
        } else {
            [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL URLWithString:model.url]];
        }
    } else if (_list.count - 1 >= _currentMusic && 0 <= _currentMusic) {
        if (_list.count - 1 > _currentMusic) {
            [HearderView shareInstance].progressSlider.value = 0;
            MusicModel *model;
            if (_orderManager == 0) {
                _currentMusic++;
                model = [_list objectAtIndex:_currentMusic];
            } else if (_orderManager == 1) {
                model = [_list objectAtIndex:_currentMusic];
            } else if (_orderManager == 2) {
                _currentMusic = random() % (_list.count - 1);
                model = [_list objectAtIndex:_currentMusic];
            }
            //            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[MusicPlayer1 shareInstance].currentMusic inSection:0];
            //            [[HearderView shareInstance].listTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            if ([MusicPlayer1 shareInstance].isDownLoad) {
                NSString *homePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
                NSString *url = [homePath stringByAppendingPathComponent:model.url];
                [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL fileURLWithPath:url]];
            } else {
                [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL URLWithString:model.url]];
            }
        } else if (_list.count - 1 == _currentMusic) {
            _currentMusic = 0;
            MusicModel *model = [_list objectAtIndex:_currentMusic];
            if ([MusicPlayer1 shareInstance].isDownLoad) {
                NSString *homePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
                NSString *url = [homePath stringByAppendingPathComponent:model.url];
                [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL fileURLWithPath:url]];
            } else {
                [[MusicPlayer1 shareInstance].moviePlayer setContentURL:[NSURL URLWithString:model.url]];
            }
        }
    }
    [self play];
}

- (void)downloadLrcId
{
    if (_list.count == 0) {
        return;
    }
    MusicModel *model = [_list objectAtIndex:_currentMusic];
    [HearderView shareInstance].title.text = [NSString stringWithFormat:@"♪  %@  ♪", model.songName];
    [HearderView shareInstance].singerName.text = model.singerName;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
    [formatter1 setDateFormat:@"mm"];
    
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
    [formatter2 setDateFormat:@"ss"];
    
    NSString *time1 = @"%2019%3A";
    NSString *time2 = @"%3A";
    NSString *songName = [NSString stringWithFormat:@"%@",model.songName];
    
    
    songName = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *date = [formatter stringFromDate:[NSDate date]];
    NSString *date1 = [formatter1 stringFromDate:[NSDate date]];
    NSString *date2 = [formatter2 stringFromDate:[NSDate date]];
    NSString *nowDate = [[[[date stringByAppendingString:time1] stringByAppendingString:date1]stringByAppendingString:time2] stringByAppendingString:date2];
    NSString *stringLast = [@"&deviceid=1C0473B8-3657-4AA2-A1C6-829FD9A36FA8&deviceusername=liusiyu0630%2540126.com&key=" stringByAppendingString:songName];
    NSString *stringLast1 = [stringLast stringByAppendingString: @"&network_type=1&page=1&searchtype=1&sign=0&singer_name=&song_name=&type=0&zone=Asia%252FShanghai%2520%2528GMT%252B8%2529"];
    NSString *nameString = [NSString stringWithFormat:@"&content=%@", model.songName];
    nameString = [nameString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *lrcUrlPath = [[[[URLPath lrcURL] stringByAppendingString:nowDate] stringByAppendingString:nameString] stringByAppendingString:stringLast1];
    
    __weak typeof(self)weakSelf = self;
    AFHTTPRequestOperationManager *managerLrc = [AFHTTPRequestOperationManager manager];
    managerLrc.responseSerializer = [AFHTTPResponseSerializer serializer];
    [managerLrc.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [managerLrc GET:lrcUrlPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        if (dic[@"info"] != nil && ![dic[@"info"] isEqual:[NSNull null]]) {
            NSDictionary *dic1 = dic[@"info"];
            NSArray *array = dic1[@"data"];
            NSDictionary *dic2 = [array firstObject];
            if (dic2[@"id"] != nil && ![dic2[@"id"] isEqual:[NSNull null]]) {
                weakSelf.lrc_id = dic2[@"id"];
                [weakSelf downloadLrc];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

- (void)downloadLrc
{
    if (_list.count == 0) {
        return;
    }
    NSString *getLrcPath = [[URLPath getLrcURL] stringByAppendingFormat:@"%@", _lrc_id];
    AFHTTPRequestOperationManager *managerDownloadLrc = [AFHTTPRequestOperationManager manager];
    __weak typeof(self)weakSelf = self;
    managerDownloadLrc.responseSerializer = [AFHTTPResponseSerializer serializer];
    [managerDownloadLrc GET:getLrcPath parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *info = dic[@"info"];
        weakSelf.lrc = info[@"lyric"];
        [[HearderView shareInstance].lrcTimer invalidate];
        [[HearderView shareInstance] initLRC];
        [[HearderView shareInstance] startLoadLrc];
        [[HearderView shareInstance].lrcTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        //        if ((lastPlayItem != self.player.currentItem)) {
        //            lastPlayItem = self.player.currentItem;
        _dict = [[NSMutableDictionary alloc]init];
        [_dict setObject:_model.songName forKey:MPMediaItemPropertyTitle];//歌曲名设置
        
        [_dict setObject:_model.singerName forKey:MPMediaItemPropertyArtist];//歌手名设置
        
        
        [_dict setObject:[[MPMediaItemArtwork alloc] initWithImage:[HearderView shareInstance].titleImageView.image]   forKey:MPMediaItemPropertyArtwork];//专辑图片设置
//        CMTime time = CMTimeMakeWithSeconds(_moviePlayer.currentPlaybackTime, 128);
//        [_dict setObject:[NSNumber numberWithDouble:(double)_moviePlayer.currentPlaybackTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐当前已经播放时间
//        NSLog(@"%f", (double)_moviePlayer.currentPlaybackTime);
        [_dict setObject:[NSNumber numberWithFloat:1.0] forKey:MPNowPlayingInfoPropertyPlaybackRate];//进度光标的速度 （这个随 自己的播放速率调整，我默认是原速播放）

//        NSString *musicLength = [NSString stringWithFormat:@"%f", _moviePlayer.duration];
        [_dict setObject:_model.musicLength forKey:MPMediaItemPropertyPlaybackDuration];//歌曲总时间设置
        
//        [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = nil;
//        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:_dict];
        
        //        }
    }
    
}

- (void)initSongInfomation
{
    if (_list.count == 0) {
        return;
    }
    MusicModel *model = [_list objectAtIndex:_currentMusic];
    _model = [MusicModel getMusicModel];
    NSString *second = [model.musicLength substringToIndex:2];
    NSString *min = [model.musicLength substringFromIndex:1];
    NSInteger totalTime = [second integerValue] + [min integerValue] * 60;
    _model.musicLength = [NSString stringWithFormat:@"%ld", (long)totalTime];
    _model.songName = model.songName;
    _model.singerName = model.singerName;
    NSString *path = [[URLPath SingerInfomationURL] stringByAppendingFormat:@"%@?detail=true&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone5C&f=f320&s=s310&imsi=&hid=&splus=8.1.3&active=1&net=2&openudid=79792c08a7dfa63c2a951b75a564d02258847fe0&idfa=5A4BDB8F-1B62-4935-BB75-F371FD524202&utdid=VXQOrj7lpYoDAEssqhP8uWqW&alf=201200&bundle_id=com.ttpod.music", model.singerId];
    __weak typeof(self)weakSelf = self;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic1 = dic[@"data"];
        if (dic1[@"picUrl"] != nil && ![dic1[@"picUrl"] isEqual:[NSNull null]]) {
            weakSelf.pic_url = dic1[@"picUrl"];
            [[HearderView shareInstance].titleImageView setImageWithURL:[NSURL URLWithString:weakSelf.pic_url] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            [[HearderView shareInstance].timer invalidate];
//            NSLog(@"%ld", [HearderView shareInstance].timer.retainCount);
            [[HearderView shareInstance].imageTurnTimer invalidate];
            [HearderView shareInstance].progressSlider.value = 0;
            [[HearderView shareInstance] startTurn];
            [weakSelf downloadLrcId];
            [[HearderView shareInstance].backgroundImageView setImageWithURL:[NSURL URLWithString:_pic_url] placeholderImage:[UIImage imageNamed:@"bgImage"]];
            weakSelf.titleImage.image = [HearderView shareInstance].titleImageView.image;
            
        } else {
            [[HearderView shareInstance].titleImageView setImage:[UIImage imageNamed:@"placeholder"]];
            [[HearderView shareInstance].timer invalidate];
            [[HearderView shareInstance].imageTurnTimer invalidate];
            [HearderView shareInstance].progressSlider.value = 0;
            [[HearderView shareInstance] startTurn];
            weakSelf.titleImage.image = [UIImage imageNamed:@"placeholder"];
            [[HearderView shareInstance].backgroundImageView setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"bgImage"]];
            [weakSelf downloadLrcId];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[HearderView shareInstance].titleImageView setImage:[UIImage imageNamed:@"placeholder"]];
        weakSelf.titleImage.image = [UIImage imageNamed:@"placeholder"];
        [[HearderView shareInstance].backgroundImageView setImage:[UIImage imageNamed:@"bgImage"]];
        [[HearderView shareInstance].timer invalidate];
        [[HearderView shareInstance].imageTurnTimer invalidate];
        [HearderView shareInstance].progressSlider.value = 0;
        [[HearderView shareInstance] startTurn];
        [self downloadLrcId];
    }];
}


- (void)loadMusicList:(NSMutableArray *)dataArray
{
    [_list removeAllObjects];
    [_list addObjectsFromArray:dataArray];
}

- (void)play
{
    _number = 0;
    _isPlay = YES;
    [HearderView shareInstance].progressSlider.value = 0;
    [[HearderView shareInstance].timer invalidate];
    [[HearderView shareInstance].imageTurnTimer invalidate];
    [[HearderView shareInstance].lrcTimer invalidate];
    [HearderView shareInstance].currentTime.text = @"00:00";
    [[HearderView shareInstance].LRCDictionary removeAllObjects];
    [[HearderView shareInstance].timeArray removeAllObjects];
    [[HearderView shareInstance].lrcTableView reloadData];
    [[HearderView shareInstance].listTableView reloadData];
    [[HearderView shareInstance].progressBar setProgress:0.0 animated:NO];
    [_moviePlayer play];
    
    NSArray *array = [Database selectData:@""];
    NSArray *downloadArray = [Database selectDownloadData];
    BOOL isOK = YES;
    BOOL isDownLoad = YES;
    MusicModel *model = [[MusicPlayer1 shareInstance].list objectAtIndex:[MusicPlayer1 shareInstance].currentMusic];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentMusic inSection:0];
    [[HearderView shareInstance].listTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    
    for (MusicModel *downloadModel in downloadArray) {
        if ([downloadModel.songId integerValue] == [model.songId integerValue]) {
            [[HearderView shareInstance].downloadBtn setImage:[UIImage imageNamed:@"iconfont-xiazaiwancheng"] forState:UIControlStateNormal];
            isDownLoad = NO;
            break;
        }
    }
    if (isDownLoad) {
        [[HearderView shareInstance].downloadBtn setImage:[UIImage imageNamed:@"iconfont-xiazai2"] forState:UIControlStateNormal];
    }
    if (_isDownLoadList) {
        [HearderView shareInstance].likeBtn.hidden = YES;
    } else {
        [HearderView shareInstance].likeBtn.hidden = NO;
    }
    
    for (MusicModel *dbModel in array) {
        if ([dbModel.songId integerValue] == [model.songId integerValue]) {
            isOK = NO;
            [[HearderView shareInstance].likeBtn setImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:UIControlStateNormal];
            break;
        }
    }
    if (isOK) {
        [[HearderView shareInstance].likeBtn setImage:[UIImage imageNamed:@"iconfont-xihuan3"] forState:UIControlStateNormal];
    }
}

@end
